﻿using EONFULLSIN.Models;
using EONFULLSIN.Utils;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace EONFULLSIN.Views.Device
{
    public partial class UserControlDeviceList : UserControl
    {
        List<DeviceModel> deviceModels = new List<DeviceModel>();
        Form form;
        private bool isKO3Warn = false;
        public bool isKO2Warn = false;
        bool isTIC32032First = true;
        public int time120s = 12;
        public int time60s = 6;
        bool isClose = false;
        int SV32013time = 0;
        private int time10m = 10;
        private int tic31031 = 0; //当CSPT/TC31031<=-20,K02启动。当CSPT/TC31031=-10,K02关闭。
        private int cspc2t = 0; //当CSPC2T=120，K02禁止启动120S
        private int tic32032 = 0; //当TIC32032=-80(首次)，K02启动120S.
        private int csp32012 = 0; //当CSP32012=50%，SV32012->5S启动（50%）,5S关闭，重复120S->一直启动。
        private int csp32013 = 0; //当CSP32013=30%,SV32013->3S启动（30%），7S关闭
        private int tic32031 = 0; //当TIC32031<=-80,K03启动,SV/CSP全关。当CSPT/TIC32031=-65，KO3关闭。
        private int cspc3t = 0; //当CSPC3T=120,KO3禁止启动120S.

        private int CSPC3P = 0; //当CSPC3P=-19，K03热气旁通。
        private int pic33007 = 0; //当PIC33007>=19，SV33015启动。当PIC33007<19，SV33015关闭。
        private string iComPort;
        public static event Action<ConcurrentDictionary<string, bool>> AnalogEvent;
        private bool k01,
            k03,
            k06;
        private bool[] com2Value,
            com1Value;
        private float X; // 当前窗体的宽度
        private float Y; // 当前窗体的高度
        private bool[] adamAValue,
            adamBValue;

        public UserControlDeviceList(Form _from)
        {
            InitializeComponent();

            form = _from;
            setData();

            UpdateData();

            ZLANTaskRun();
            JYTaskRun();
            AdamTaskRun();
        }
        private void ZLANTaskRun()
        {
            Task.Run(() =>
            {
                ModbusZlanHelper zlanHelper = new ModbusZlanHelper();
                zlanHelper.getData();
            });
        }

        private void AdamTaskRun()
        {
            Task.Run(() =>
            {
                adamAValue = Program.adamA.getData();
                adamBValue = Program.adamB.getData();
                for (int i = 0; i < adamAValue?.Length; i++)
                {
                    deviceModels[i + 40].value = adamAValue[i] + "";
                }
                for (int i = 0; i < adamAValue?.Length; i++)
                {
                    deviceModels[i + 32].value = adamBValue[i] + "";
                }
                if (this.IsHandleCreated)
                {
                    this.Invoke(
                        new Action(() =>
                        {
                            UpdateData();
                        })
                    );
                }
            });
        }

        private void JYTaskRun()
        {
            Task.Run(async () =>
            {
                ModbusJYHelper jYHelper = new ModbusJYHelper();
                while (true)
                {
                    ushort[] jyValue = await jYHelper.getData();
                    if (this.IsHandleCreated)
                    {
                        this.Invoke(
                            new Action(() =>
                            {
                                for (int i = 0; i < jyValue?.Length; i++) {
                                    ////前20位为温度传感器
                                    //if (i < 20 && jyValue[i] > 1000)
                                    //{
                                    //    deviceModels[i].value =
                                    //        ParseHelper.MapValue(
                                    //            (double)jyValue[i] / 1000,
                                    //            -150,
                                    //            150
                                    //        ) + "℃";
                                    //}
                                    //else if (i > 23 && i < 27 && jyValue[i] > 1000) //压力传感器1
                                    //{
                                    //    deviceModels[i].value =
                                    //        ParseHelper.MapValue((double)jyValue[i] / 1000, -0.1, 1)
                                    //        + "MPa";
                                    //}
                                    //else if (i > 26 && i < 30 && jyValue[i] > 1000) //压力传感器2
                                    //{
                                    //    deviceModels[i].value =
                                    //        ParseHelper.MapValue((double)jyValue[i] / 1000, 0, 2.5)
                                    //        + "MPa";
                                    //}
                                    //else //其他
                                    //{
                                    //    deviceModels[i].value = jyValue[i] + "";
                                    //}

                                    if (i < 3 && jyValue[i] > 1000) //压力传感器1
                                     {
                                        deviceModels[i].value =
                                            ParseHelper.MapValue((double)jyValue[i] / 1000, -0.1, 1)
                                            + "MPa";
                                    } else if (i > 3 && i < 6 && jyValue[i] > 1000) //压力传感器2
                                      {
                                        deviceModels[i].value =
                                            ParseHelper.MapValue((double)jyValue[i] / 1000, 0, 2.5)
                                            + "MPa";
                                    } else if (i > 7 && i < 24 && jyValue[i] > 1000) {
                                        deviceModels[i].value =
                                            ParseHelper.MapValue(
                                                (double)jyValue[i] / 1000,
                                                -150,
                                                150
                                            ) + "℃";
                                    } else //其他
                                      {
                                        deviceModels[i].value = jyValue[i] + "";
                                    }

                                }
                                UpdateData();
                            })
                        );
                    }
                    Task.Delay(5000).Wait();
                }
            });
        }

        private void UpdateData()
        {
            for (int i = 0; i < deviceModels.Count; i++)
            {
                dataGridView1.Rows[i].Cells[0].Value = deviceModels[i].name.ToString();
                dataGridView1.Rows[i].Cells[1].Value = deviceModels[i].type.ToString();
                dataGridView1.Rows[i].Cells[2].Value = deviceModels[i].value.ToString();
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            if (button1.Text == "-80启动")
            {
                button1.Text = "-80停止";

                F80Start();
            }
            else if (button1.Text == "-80停止")
            {
                F80Stop();
                button1.Text = "-80启动";
            }
        }

        private void reset()
        {
            isKO3Warn = false;
            isKO2Warn = false;
            isTIC32032First = true;
            isClose = false;
        }

        public async void F80Start()
        {
            await RelayRun("k06", time60s);
            await RelayRun("k01", time120s);
            await TaskAD001();
            await TaskAG001();
        }

        private async void F80Stop()
        {
            RelayStop("KO3");

            SVStart("SV33015");
            await Task.Run(async () =>
                {
                    for (global::System.Int32 i = 0; i < time120s; i++)
                    {
                        Trace.WriteLine("KO2 stop for ready-->" + i);
                        Task.Delay(1000).Wait();
                    }
                })
                .ContinueWith(async t =>
                {
                    RelayStop("KO2");
                });
            await StopTIC31031Run();
        }

        private async Task RelayRun(string name, int time)
        {
            await Task.Run(async () =>
                {
                    RelayStart(name);

                    for (int i = 0; i < time; i++)
                    {
                        Trace.WriteLine($"Task is running... {i}");
                        Task.Delay(1000).Wait(); // 模拟耗时操作
                    }
                })
                .ContinueWith(t =>
                {
                    RelayStop(name);
                });
        }

        public async Task TIC32032Run()
        {
            Trace.WriteLine("tic32032->" + tic32032);
            if (tic32032 == -80 && isTIC32032First)
            {
                isTIC32032First = false;
                K02Run();
                await Task.Run(async () =>
                    {
                        for (int i = 0; i < time120s; i++)
                        {
                            Trace.WriteLine($"KO2 启动... {i}");
                            Task.Delay(1000).Wait(); // 模拟耗时操作
                        }
                    })
                    .ContinueWith(t =>
                    {
                        RelayStop("KO2");
                    });
            }
        }

        private void K02Run()
        {
            if (isKO2Warn == false)
            {
                RelayStart("KO2");
            }
        }

        public void TIC31031Run()
        {
            Trace.WriteLine("cspt31031->" + tic31031);
            if (tic31031 <= -20)
            {
                K02Run();
            }
            else if (tic31031 == -10)
            {
                RelayStop("KO2");
            }
        }

        public async Task CSPC2TRun()
        {
            Trace.WriteLine("cspc2t->" + cspc2t);
            if (cspc2t == 120)
            {
                isKO2Warn = true;
                await Task.Run(async () =>
                    {
                        for (int i = 0; i < time120s; i++)
                        {
                            Trace.WriteLine($"KO2 禁止运行... {i}");
                            Task.Delay(1000).Wait(); // 模拟耗时操作
                        }
                    })
                    .ContinueWith(t =>
                    {
                        isKO2Warn = false;
                    });
            }
        }

        public async Task CSP32013Run()
        {
            Trace.WriteLine("csp32013->" + csp32013);
            if (csp32013 == 30)
            {
                await Task.Run(async () =>
                {
                    while (isClose == false)
                    {
                        if (SV32013time % 10 < 3)
                        {
                            SVStart("SV32013");
                            Trace.WriteLine($"SV32013 启动... {SV32013time}");
                        }
                        else
                        {
                            SVStop("SV32013");
                            Trace.WriteLine($"SV32013 关闭... {SV32013time}");
                        }
                        SV32013time++;
                        Thread.Sleep(1000);
                    }
                });
            }
        }

        public async Task CSP32012Run()
        {
            Trace.WriteLine("csp32012->" + csp32012);
            if (csp32012 == 50)
            {
                await Task.Run(async () =>
                    {
                        for (int i = 0; i < time120s; i++)
                        {
                            int result = i % 10;
                            if (result < 5)
                            {
                                SVStart("SV32012");
                                Trace.WriteLine($"SV32012 启动... {i}");
                            }
                            else
                            {
                                SVStop("SV32012");
                                Trace.WriteLine($"SV32012 关闭... {i}");
                            }

                            Task.Delay(1000).Wait(); // 模拟耗时操作
                        }
                    })
                    .ContinueWith(t =>
                    {
                        SVStart("SV32012");
                    });
            }
        }

        public void CloseValve()
        {
            isClose = true;
            SVStop("SV32013");
            SVStop("SV33015");
            CSPStop("CSP32012");
            CSPStop("CSP32013");
        }

        public async Task TIC32031Run()
        {
            Trace.WriteLine("tic32031-->" + tic32031);
            await Task.Run(async () =>
            {
                if (tic32031 <= -80 && isKO3Warn == false)
                {
                    KO3Run();
                    CloseValve();
                }
                else if (tic32031 == -65)
                {
                    RelayStop("KO3");
                }
            });
        }

        private void KO3Run()
        {
            if (isKO3Warn == false)
            {
                RelayStart("K03");
            }
        }

        public void SVStart(string name)
        {
            Trace.WriteLine(name + "start");
            Toast.Show(this.form, name + "start");
        }

        public async Task CSPC3TRun()
        {
            Trace.WriteLine("cspc3t->" + cspc3t);
            if (cspc3t == 120)
            {
                isKO3Warn = true;
                await Task.Run(async () =>
                    {
                        for (int i = 0; i < time120s; i++)
                        {
                            Trace.WriteLine($"KO3 disable... {i}");
                            Task.Delay(1000).Wait(); // 模拟耗时操作
                        }
                    })
                    .ContinueWith(t =>
                    {
                        isKO3Warn = false;
                    });
            }
        }

        public void SVStop(string name)
        {
            Trace.WriteLine(name + "stop");
        }

        public void RelayStart(string name)
        {
            Trace.WriteLine("Relay->" + name + "start");
            Toast.Show(this.form, name + "start");
        }

        public void RelayStop(string name)
        {
            Trace.WriteLine(name + "stop");
            Toast.Show(this.form, name + "stop");
        }

        public void CSPStop(string name)
        {
            Trace.WriteLine(name + "stop");
        }

        public void PIC3307Run()
        {
            Trace.WriteLine("pic33007->" + pic33007);
            if (pic33007 >= 19)
            {
                SVStart("SV33015");
            }
            else
            {
                SVStop("SV33015");
            }
        }

        public async Task StopTIC31031Run()
        {
            Trace.WriteLine("tic31031-->" + tic31031);
            if (tic31031 > -20)
            {
                await Task.Run(async () =>
                {
                    Trace.WriteLine("TIC31031 run delay");
                    Task.Delay(time10m).Wait();
                });
                await TaskAD001();
                await TaskAG001();
            }
        }

        public async Task TaskAD001()
        {
            Trace.WriteLine("<--TaskAD001-->");
            TIC31031Run();
            await CSPC2TRun();

            await TIC32032Run();

            await CSP32012Run();
            await CSP32013Run();
        }

        public async Task TaskAG001()
        {
            Trace.WriteLine("<--TaskAGOO1 start-->");
            await TIC32031Run();
            await CSPC3TRun();
            PIC3307Run();
            await StartTIC31031Run();
        }

        public async Task StartTIC31031Run()
        {
            Trace.WriteLine("tic31031-->" + tic31031);
            if (tic31031 > -80)
            {
                await Task.Run(async () =>
                {
                    for (global::System.Int32 i = 0; i < time10m; i++)
                    {
                        Trace.WriteLine("tic31031 loading restart->" + i);
                        Task.Delay(1000).Wait();
                    }
                });
                reset();
                await TaskAG001();
            }
        }

        private void setData()
        {
            int count = 48;
            dataGridView1.RowCount = count;
            for (int i = 0; i < count; i++)
            {
                if (i < 32)
                {
                    deviceModels.Add(
                        new DeviceModel
                        {
                            id = i,
                            name = "jy-" + (i + 1),
                            type = "",
                            value = "",
                        }
                    );
                }
                else if (i > 31 & i < 40)
                {
                    deviceModels.Add(
                        new DeviceModel
                        {
                            id = i,
                            name = "COM2-" + (i - 32),
                            type = "",
                            value = "",
                        }
                    );
                }
                else
                {
                    deviceModels.Add(
                        new DeviceModel
                        {
                            id = i,
                            name = "COM1-" + (i - 40),
                            type = "",
                            value = "",
                        }
                    );
                }
            }
        }
    }
}
